/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pnt.server;

import java.io.IOException;
import java.net.*;
import java.util.logging.Logger;

/**
 *
 * @author andrew
 */
public class UDPListener extends ConnectionListener {

    @SuppressWarnings("unused")
	private static Logger logger = Logger.getLogger("pnt.server"); 
    
    ConnectionManager conmgr;
    
    DatagramSocket primarySocket;
    boolean running = false;
    
    public UDPListener(int port, ConnectionManager conmgr){
        try {
            
            this.conmgr = conmgr;
            primarySocket = new DatagramSocket(port);
            
        } catch (SocketException ex) {
            
            System.err.println("Error establishing UDP Socket." + ex);
        
        }
    }
    
    public void run() {
		running = true;
		while(running){
		    try{
			// Packet
			byte[] message = new byte[128];
			DatagramPacket packet = new DatagramPacket(message, 128);
                        
			primarySocket.receive(packet);

                        conmgr.processMessage(packet, primarySocket);
                        
		    } catch (IOException ex) {
                        
			System.err.println("Unable to create UDP socket connection." + ex);
                        
		    }
			
		}
    }

    public boolean stop() {
        primarySocket.close();
        running = false;
        return true;
    }



}
